﻿using Net35.Xrm.Sdk.Client;
using System;
using System.ServiceModel.Description;

namespace Net35.Xrm.Sdk.Helpers
{

	public class CrmWrapper
	{
		AuthenticationCredentials _credentials = null;
		DateTime? _lastAuthenticated = null;
		object _intializeAuthenticate = new object();
		IServiceManagement<IOrganizationService> _manager;
		//string _username;
		//string _password;

		ClientCredentials _clientCredentials = null;

		public CrmWrapper(Uri serviceUri, string username, string password)
		{
			_manager = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(serviceUri);
			//_username = username;
			//_password = password;
			_clientCredentials = new ClientCredentials()
			{
				UserName = { UserName = username, Password = password }
			};
		}

		public OrganizationServiceProxy getProxy()
		{
			if (_manager.AuthenticationType == AuthenticationProviderType.ActiveDirectory)
			{
				return new OrganizationServiceProxy(_manager, _clientCredentials);
			}
			else
			{
				if (!_lastAuthenticated.HasValue || _lastAuthenticated.Value < DateTime.Now.AddHours(-2))
				{
					lock (_intializeAuthenticate)
					{
						if (!_lastAuthenticated.HasValue || _lastAuthenticated.Value < DateTime.Now.AddHours(-2))
						{
							_lastAuthenticated = DateTime.Now;
							_credentials = _manager.Authenticate(
								new AuthenticationCredentials()
								{
									ClientCredentials = _clientCredentials
								}
							);
						}
					}
				}
				return new OrganizationServiceProxy(_manager, _credentials.ClientCredentials);
			}
		}
	}
}